<?php

namespace app\common\service;

use app\model\PlatformConfigModel;
use EasyWeChat\Kernel\Exceptions\Exception;
use EasyWeChat\MiniApp\Application;
use Symfony\Component\HttpFoundation\HeaderBag;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;

class WeChatMnpService
{

    protected $app;

    protected $config;

    public function __construct()
    {
        // 从数据库获取微信小程序配置
        $config = $this->getWeChatConfig();

        $app = new Application($config);

        $symfony_request = new SymfonyRequest(request()->get(), request()->post(), [], request()->cookie(), [], [], request()->rawBody());
        $symfony_request->headers = new HeaderBag(request()->header());

        $app->setRequestFromSymfonyRequest($symfony_request);//必须替换服务端请求

        $this->app = $app;
        $this->config = $config;
    }

    /**
     * 获取微信小程序配置
     * @return array
     * @throws Exception
     */
    private function getWeChatConfig(): array
    {
        try {
            // 从数据库获取配置
            $configData = PlatformConfigModel::getConfig('wechat_mnp');

            // 验证必要的配置项
            $requiredFields = ['app_id', 'secret'];
            foreach ($requiredFields as $field) {
                if (empty($configData[$field])) {
                    throw new Exception("微信小程序配置缺少必要参数: {$field}");
                }
            }
            
            return $configData;
        } catch (\Exception $e) {
            throw new Exception('获取微信小程序配置失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取当前配置
     * @return array
     */
    public function getConfig(): array
    {
        return $this->config;
    }

    public function getServer()
    {
        return $this->app->getServer();
    }

    /**
     * @notes 小程序-根据code获取微信信息
     * @param string $code
     */
    public function getMnpResByCode(string $code)
    {
        $utils = $this->app->getUtils();
        $response = $utils->codeToSession($code);

        if (!isset($response['openid']) || empty($response['openid'])) {
            throw new Exception('获取openID失败');
        }

        return $response;
    }

    /**
     * @notes 检查一段文本是否含有违法违规内容
     * @param $openid
     * @param $content
     */
    public function msgSecCheck($openid, $content)
    {
        $checkResJson = $this->app->getClient()->postJson('wxa/msg_sec_check', [
            'openid' => $openid,
            'content' => $content,
            'scene' => 3,
            'version' => 2,
        ]);
        $checkRes = json_decode($checkResJson);


        if ($checkRes->result->label == 100) {
            return true;
        }

        return false;
    }

    /**
     * @notes 异步校验图片/音频是否含有违法违规内容
     * @param $openid
     * @param $content
     */
    public function mediaCheckAsync($openid, $mediaUrl, $mediaType = 2)
    {
        return $this->app->getClient()->postJson('wxa/media_check_async', [
            'openid' => $openid,
            'media_url' => $mediaUrl,
            'media_type' => $mediaType, // 1:音频;2:图片
            'version' => 2,
            'scene' => 3,
        ]);
    }

    /**
     * 发送订阅消息
     */
    public function sendSubscribeMessage(string $templateId, $touser, $page, $data)
    {
        return $this->app->getClient()->postJson('cgi-bin/message/subscribe/send', [
            'template_id' => $templateId,
            'page' => $page,
            'touser' => $touser,
            'data' => $data,
            'miniprogram_state' => 'formal',
            'lang' => 'zh_CN'
        ]);
    }

    /**
     * @notes 获取小程序二维码
     * @param string $code
     */
    public function getQrCode(string $page, string $scene)
    {
        return $this->app->getClient()->postJson('wxa/getwxacodeunlimit', [
            'page' => $page,
            'scene' => $scene
        ]);
    }

    /**
     * 获取ShortLink
     */
    public function getShortLink(string $pageUrl)
    {
        return $this->app->getClient()->postJson('wxa/genwxashortlink', [
            'page_url' => $pageUrl
        ]);
    }

    /**
     * 获取scheme码
     */
    public function generateScheme(string $pagePath = '', $query = '')
    {
        return $this->app->getClient()->postJson('wxa/generatescheme', [
            'jump_wxa' => [
                'path' => $pagePath,
                'query' => $query,
//                'env_version' => 'trial'
            ]
        ]);
    }

    /**
     * 查询scheme码
     */
    public function queryscheme($scheme)
    {
        return $this->app->getClient()->postJson('wxa/queryscheme', [
            'scheme' => $scheme
        ]);
    }
}